package com.demo0228.demo01;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

public class Dom4jDemo {

    @Test
    public void readXML1() throws Exception {
        //第一步： 先加载xml 文件创建 Document对象
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(Dom4jDemo.class.getResourceAsStream("/demo0228/books.xml"));
        System.out.println(document);
        //第二步：通过Document 对象拿到根元素对象
        Element root = document.getRootElement();
        System.out.println(root);
        //将文档以XML形式打印
        System.out.println(root.asXML());
        System.out.println("XML文档输出完毕");
        //第三步：通过根元素 .elements(标签名 );可以返回一个集合，这个集合里放着。所有你指定的标签名的元素对象
        List<Element> bookList = root.elements("book");
        for (int i = 0; i < bookList.size(); i++) {
            Element book = bookList.get(i);
            //读取 book 标签的属性 ISBN
            String isbn = book.attributeValue("ISBN");
            System.out.println("ISBN = " + isbn);
            //获取子元素
            Element bookName = book.element("book-name");
            Element price = book.element("price");
            Element author = book.element("author");
            Element num = book.element("num");
            Element category = book.element("category");
            System.out.println("bookName = " + bookName.getText());
            System.out.println("price = " + price.getText());
            System.out.println("author = " + author.getText());
            System.out.println("num = " + num.getText());
            System.out.println("category = " + category.getText());
            System.out.println("book标签解析结束");
        }
        //第四步：找到你想要修改、删除的子元素，进行相应在的操作
    }
}
